import { MockMethod } from 'vite-plugin-mock';
import { resultSuccess, resultError, baseUrl } from '../_util';

const list: Recordable[] = [
  {
    id: 1,
    name: '张三',
    gender: 'male',
    organization: 'unknown',
    orgCode: 'xxx1',
    remark: '是个好人'
  },
  {
    id: 2,
    name: '李四',
    gender: 'male',
    organization: 'unknown',
    orgCode: 'xxx2',
    remark: 'bad guy'
  },
  {
    id: 3,
    name: '韩梅梅',
    gender: 'female',
    organization: '东方红小学',
    orgCode: 'xxx3',
    remark: 'smart student'
  },
]

export default [
  {
    url: `${baseUrl}/interviewee/list`,
    timeout: 1000,
    method: 'get',
    response: ({ query }) => {
      const { name, gender } = query
      let filtered = list.slice()
      if (name) {
        filtered = filtered.filter(item => item.name.includes(name))
      }
      if (gender) {
        filtered = filtered.filter(item => item.gender === gender)
      }
      return resultSuccess(filtered)
    }
  },
  {
    url: `${baseUrl}/interviewee/add`,
    // timeout: 1000,
    statusCode: 200,
    method: 'post',
    response: ({ body }) => {
      let id = 1
      list.forEach(item => { id = item.id > id ? item.id : id })
      id++

      // const { data } = JSON.parse(body)
      body.id = id
      body.orgCode = 'xxx' + id
      list.push(body)
      return resultSuccess({ saved: id })
    }
  },
  {
    url: `${baseUrl}/interviewee/delete`,
    statusCode: 200,
    method: 'delete',
    response: ({ body }) => {
      // return resultSuccess({ delete: body })
      const { id } = body
      let deleted = false
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === id) {
          list.splice(i, 1)
          deleted = true
          break
        }
      }
      if (deleted) {
        return resultSuccess({ deleted: true })
      }
      return resultError('fail')
    }
  },
  {
    url: `${baseUrl}/interviewee/edit`,
    statusCode: 200,
    method: 'post',
    response: ({ body }) => {
      const { id } = body
      const index = list.findIndex(item => item.id === id)
      if (index === -1) { return resultError('fail') }
      list.splice(index, 1, body)
      return resultSuccess({ saved: true })
    }
  },
] as MockMethod[];
